const { prisma } = require('../config/prisma');

/**
 * 卡密兑换
 */
const exchangeCard = async (req, res) => {
  try {
    const { card_no } = req.body;

    if (!card_no) {
      return res.status(400).json({
        code: 400,
        message: '卡密不能为空'
      });
    }

    // 查找并锁定卡密
    const card = await prisma.card.findFirst({
      where: {
        cardNo: card_no,
        status: 0 // 未使用
      }
    });

    if (!card) {
      return res.status(400).json({
        code: 400,
        message: '无效的卡密'
      });
    }

    // 开启事务处理兑换流程
    const result = await prisma.$transaction(async (prisma) => {
      // 再次检查卡密状态（防止并发）
      const currentCard = await prisma.card.findFirst({
        where: {
          id: card.id,
          status: 0
        }
      });

      if (!currentCard) {
        throw new Error('Card already used');
      }

      // 更新卡密状态
      await prisma.card.update({
        where: { id: card.id },
        data: {
          status: 1,
          usedUserId: req.user.id,
          usedTime: new Date()
        }
      });

      // 计算会员到期时间
      const now = new Date();
      const user = await prisma.user.findUnique({
        where: { id: req.user.id }
      });

      let expireTime;
      if (user.memberType > 0 && user.expireTime > now) {
        // 如果是已有会员，在当前到期时间基础上增加天数
        expireTime = new Date(user.expireTime.getTime() + card.days * 24 * 60 * 60 * 1000);
      } else {
        // 如果不是会员，从当前时间开始计算
        expireTime = new Date(now.getTime() + card.days * 24 * 60 * 60 * 1000);
      }

      // 更新用户会员信息
      const updatedUser = await prisma.user.update({
        where: { id: req.user.id },
        data: {
          memberType: card.memberType,
          expireTime
        }
      });

      return {
        memberType: updatedUser.memberType,
        expireTime: updatedUser.expireTime
      };
    });

    res.json({
      code: 0,
      data: {
        member_type: result.memberType,
        days: card.days,
        expire_time: result.expireTime
      }
    });
  } catch (error) {
    console.error('Exchange card error:', error);
    if (error.message === 'Card already used') {
      return res.status(400).json({
        code: 400,
        message: '卡密已被使用'
      });
    }
    res.status(500).json({
      code: 500,
      message: '卡密兑换失败'
    });
  }
};

module.exports = {
  exchangeCard
}; 